import * as morgan from 'morgan';
import * as dayjs from 'dayjs';
import * as express from 'express';

export function getClientIp(req: express.Request): string {
    return (
        req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection['socket'].remoteAddress ||
        ''
    );
}

/**
 * 日志系统
 */
export const logSystemInterceptor = morgan(function (tokens, req, res) {
    const extractData = (key, data) => {
        if (!data || Object.keys(data).length == 0) {
            return '';
        }
        return `${key}=${JSON.stringify(data).slice(0, 100)}`;
    };
    return [
        dayjs().format('YYYY-MM-DD HH:mm:ss'),
        tokens.method(req, res),
        tokens.url(req, res),
        tokens.status(req, res),
        tokens.res(req, res, 'content-length'),
        '-',
        tokens['response-time'](req, res),
        'ms',
        extractData('body', req['body']),
        `Headers: authorization=${req.headers.authorization || ''}`,
        `Headers: adminuid=${req.headers.adminuid || ''}`,
        `client ip address=${getClientIp(req as any)}`,
    ]
        .filter((it) => it && it.length)
        .join(' ');
});
